package com.neo.v1;

import com.neo.util.CommonUtil;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

import static com.neo.util.SystemUtil.printMsg;

/**
 * 1.3.7
 * 演示主线程与子线程并行执行
 */
public class V137MainWithThreadCron {

	private static final int COMPUTE_TIMES = 100;


	public static void main(String[] args) throws InterruptedException {
		ReturnableTask returnableTask = new ReturnableTask();
		FutureTask<Long> futureTask = new FutureTask<>(returnableTask);
		Thread thread = new Thread(futureTask, "returnableThread");
		thread.start();
		Thread.sleep(500);
		printMsg(CommonUtil.getCurThreadInfo() + " 让子弹飞一会会会儿!!!");
		printMsg(CommonUtil.getCurThreadInfo()+" 做一些自己的事情");
		for (int i = 0; i < COMPUTE_TIMES / 2; i++) {

			int j = i*1000;
			printMsg(CommonUtil.getCurThreadInfo() + System.currentTimeMillis()+ " "+j);
		}

		printMsg(CommonUtil.getCurThreadInfo() + "获取并发任务执行结果:");

		try {
			printMsg(thread.getName() + " 线程占用时间 "+ futureTask.get());
		} catch (ExecutionException e) {
			e.printStackTrace();
		}

		printMsg(CommonUtil.getCurThreadInfo() + " 运行结束");
	}

	public static class ReturnableTask implements Callable<Long>{

		/**
		 * Computes a result, or throws an exception if unable to do so.
		 *
		 * @return computed result
		 * @throws Exception if unable to compute a result
		 */
		@Override
		public Long call() throws Exception {
			long startTime = System.currentTimeMillis();
			printMsg(CommonUtil.getCurThreadInfo() + " start=>");
			Thread.sleep(1000);
			for (int i = 0; i < COMPUTE_TIMES; i++) {

				int j = i* 10000;
				printMsg(CommonUtil.getCurThreadInfo() + System.currentTimeMillis() + " "+j);
			}

			printMsg(CommonUtil.getCurThreadInfo() + " end <=");
			return System.currentTimeMillis() - startTime;

		}
	}





}